export default{
  namespaced:true,
  //模块的state数据
  state:()=>({
    cart:JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  mutations:{
    addCart(state,goods){
      //判断商品是否存在,如果存在则返回当前商品信息
      const findResult = state.cart.find((x) => x.goods_id == goods.goods_id)
      console.log(findResult);
      if(!findResult){
        //商品不存在
        state.cart.push(goods)
      }else{
        //如果商品存在,则商品数量+1
        findResult.goods_count++
      }
      //通过commit方法，调用m_cart命名空间下的saveToStorage方法
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //修改商品的勾选状态
    updateGoodsState(state,goods){
      //通过传过来的id于state中数据比较，取出当前商品的信息
      const findResult = state.cart.find(x=>
        x.goods_id === goods.goods_id
      )
      console.log(findResult);
      if(findResult){
        //修改商品状态
        findResult.goods_state = goods.goods_state
        //持久化存储到本地
        this.commit('m_cart/saveToStorage')
      }
    },
    //修改商品数量
    updateGoodsCount(state,goods){
      const findResult = state.cart.find(x=>
      x.goods_id == goods.goods_id
      )
      console.log(findResult);
      if(findResult){
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    removeGoodsById(state,goods_id){
      const findResult = state.cart.filter(x =>
      x.goods_id!=goods_id)
      if(findResult){
        state.cart = findResult
        this.commit('m_cart/saveToStorage')
      }
    },
    //更新所有商品的勾选状态，反选
    updateAllGoodsState(state,newState){
      state.cart.forEach(item => item.goods_state = newState) 
      //持久化存储到本地
      this.commit('m_cart/saveToStorage')
    }
    
  },
  getters:{
    //商品数量
    total(state){
      let c = 0
      state.cart.forEach(goods=> c+=goods.goods_count)
      return c
    },
    //已勾选商品总数量
    checkedCount(state){
      return state.cart.filter(i => i.goods_state).reduce((total,item) => total+=item.goods_count,0)
    },
    //已勾选商品总价格
    checkedGoodsAmount(state){
      return state.cart.filter(i => i.goods_state).reduce((sum,item)=>sum += item.goods_count*item.goods_price,0)
    },
    //是否至少有一件商品被勾选
    checkedOne(state){
      return state.cart.filter(i => i.goods_state).reduce((sum,item)=>sum+=item.goods_count,0)
    }
    
    
  },
}